<?php
header('Content-Type: text/plain');
require_once dirname(__FILE__) . '/__cdb.conf.php';

try {
  $myPdo = new PDO("mysql:host=$host", $login, $pass);
  $myPdo->exec("USE $db_using");
  $myPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
}

$action = $_POST['action'];

try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'miss_table':
      miss_table($myPdo);
      break;
    case 'miss_field':
      miss_field($myPdo);
      break;
    case 'diff_type':
      diff_type($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  __dump($e); 
}

function miss_table($myPdo) {
  $table = $_POST['table'];
  $content = json_decode($_POST['content']);
  $myPdo->exec(__miss_table_sql($table, $content));
}

function miss_field($myPdo) {
  $table = $_POST['table'];
  $content = json_decode($_POST['content']);
  foreach ($content as $column => &$type) {
    $sql = "ALTER TABLE `$table` ADD `$column` " . __type_sql($type) . ';';
    $myPdo->exec($sql);
  }
  foreach ($content as $column => &$type) {
    if ($type->Key == 'MUL') {
      $sql = "CREATE INDEX $column ON $table ($column);";
      $myPdo->exec($sql);
    }
  }
}

function diff_type($myPdo) {
  $table = $_POST['table'];
  $content = json_decode($_POST['content']);
  foreach ($content as $column => &$type) {
    $sql = "ALTER TABLE `$table` MODIFY `$column` " . __type_sql($type) . ';';
    $myPdo->exec($sql);
  }
  foreach ($content as $column => &$type) {
    if ($type->Key == 'MUL') {
      $sql = "CREATE INDEX $column ON $table ($column);";
      $myPdo->exec($sql);
    } else {
      $sql = "DROP INDEX $column ON $table ($column);";
      $myPdo->exec($sql);
    }
  }
}

function __miss_table_sql($table, $content) {
  $sql = "CREATE TABLE IF NOT EXISTS `$table` (";
  $total = count((array)$content);
  $count = 1;
  foreach ($content as $column => &$type) {
    $sql .= "`$column` " . __type_sql($type);
    if ($count != $total) {
      $sql .= ', ';
    }
    $count++;
  }
  $sql .= ') ENGINE=MYISAM;';
  foreach ($content as $column => &$type) {
    if ($type->Key == 'MUL') {
      $sql .= "CREATE INDEX $column ON $table ($column);";
    }
  }
  return $sql;
}

function __type_sql($type) {
  $sql = $type->Type;
  $sql .= ($type->Null == 'YES') ? '' : ' NOT NULL';
  if ($type->Extra == 'auto_increment') {
    $sql .= ' AUTO_INCREMENT';
  }
  if ($type->Key == 'PRI') {
    $sql .= ' PRIMARY KEY';
  }
  if ($type->Key == 'UNI') {
    $sql .= ' UNIQUE';
  }
  if ($type->Default != '') {
    $sql .= ' DEFAULT ' . $type->Default;
  }
  return $sql;
}
?>